package pqt;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class SelectorFallas extends JDialog {

	private final JPanel contentPanel = new JPanel();
	
	final ImageIcon icon = new ImageIcon(SelectorFallas.class.getResource("/img/error.png"));
	
	List lista = new List();
	
	private Bloque bloque;
	
	private JList list;
	
	private String item;
	
	private int indexItem;
	
	final JButton btnAceptar = new JButton("");
	
	private KeyAdapter keyAdapter; 
	
	JButton btnMarcarTodas = new JButton("Marcar Todas");
	
	JButton btnDescarcarTodas = new JButton("Desmarcar Todas");
	
	public SelectorFallas(Bloque bloque, int indexItem, String item) {
		setTitle("Seleccione Falla/s:");
		
		this.bloque = bloque;
		this.item = item;
		this.indexItem = indexItem;
		
		for(int i=0;i<bloque.getFallasCount();i++)
		lista.add(bloque.getNombreFalla(i));
		
		mostrarAtributos();
	}
	
	public void mostrarAtributos() {
		
		
		
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		
		int altoPantalla = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;
		int anchoPantalla = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
		int anchoFrame = (int)(anchoPantalla*0.4);
		int altoFrame = (int)(altoPantalla*0.8);
		setBounds(0,0,761,522);
		setBounds(300, altoPantalla-altoFrame-40,anchoFrame,altoFrame);
		
		//setUndecorated(true);
		
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBackground(new Color(240, 240, 240));
		//contentPanel.setBorder(new TitledBorder(new LineBorder(new Color(53, 85, 134), 2), item.toUpperCase(), TitledBorder.LEFT, TitledBorder.TOP, null, null));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		setResizable(false);
		lista.add("Otros");
		list = new JList(createLista(lista));
		list.setFont(new Font("Tahoma", Font.PLAIN, 17));
		final JScrollPane scrollPane = new JScrollPane(list);
		scrollPane.setBounds(10, 59, anchoFrame-20, 375);
		contentPanel.add(scrollPane);
		list.setCellRenderer(new CheckListRenderer());
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.setBorder(new EmptyBorder(0, 4, 0, 0));
		list.setFocusable(false);
		btnAceptar.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				
				System.out.println("asd");
				if(e.getKeyCode() == KeyEvent.VK_SPACE){
					   e.consume();
					   btnMarcarTodas.doClick();
				   }
				
				if(e.getKeyCode() == KeyEvent.VK_F1){
					   e.consume();
					   btnDescarcarTodas.doClick();
				   }
				
				if(e.getKeyCode() == KeyEvent.VK_ENTER){
					   
					   //if(table.getSelectedRow() == table.getRowCount()-1){
					    	e.consume();
					    	btnAceptar.doClick();
					    //}
					    //btnAceptar.requestFocus();
					   
				   }
				   			   
				   
				   
			}
		});
		
		
		btnAceptar.setFocusable(true);
		btnAceptar.setContentAreaFilled(false);
		btnAceptar.setBorderPainted(false);
		btnAceptar.setBorder(null);
		btnAceptar.setBounds((anchoFrame/2)-132, 500, 265, 75);
		btnAceptar.setIcon(new ImageIcon(SelectorFallas.class.getResource("/img/AceptarVerdeChico.png")));
		
				
		btnAceptar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				
				if(imprimirTodos()) {
				dispose();
				}
				else
				{
					JOptionPane.showOptionDialog(
			                null,
			                "<html><h1>Por favor, seleccione una falla.</h1></html>",
			                "Error al ingresar",
			                JOptionPane.OK_OPTION,
			                JOptionPane.INFORMATION_MESSAGE,
			                icon,
			                new Object[]{"Aceptar"},
			                "Aceptar");
				}
				
				
			}
		});
		
		/*btnAceptar.addMouseListener(new MouseAdapter() {
					
			public void mouseEntered(MouseEvent arg0) {
				//btnAceptar.setIcon(new ImageIcon(PuestaCero.class.getResource("/img/AceptarVerdeChico.png")));
				//btnCancelar.setIcon(new ImageIcon(PuestaCero.class.getResource("/img/CancelarNegroChico.png")));
				//getRootPane().setDefaultButton(btnAceptar);
						
			}
					
			
		});
				
		btnAceptar.addFocusListener(new FocusAdapter() {
				
			public void focusGained(FocusEvent arg0) {
				//btnAceptar.setIcon(new ImageIcon(PuestaCero.class.getResource("/img/AceptarVerdeChico.png")));
				//btnCancelar.setIcon(new ImageIcon(PuestaCero.class.getResource("/img/CancelarNegroChico.png")));
				//getRootPane().setDefaultButton(btnAceptar);
				
				
			}
					
			public void focusLost(FocusEvent e) {
				//btnAceptar.setIcon(new ImageIcon(PuestaCero.class.getResource("/img/AceptarNegroChico.png")));
				
			}
		});*/
		contentPanel.add(btnAceptar);
		
		
		btnMarcarTodas.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				marcarTodas();
			}
		});
		btnMarcarTodas.setBounds(10, 445, 161, 23);
		btnMarcarTodas.setFocusable(false);
		contentPanel.add(btnMarcarTodas);
		
		
		btnDescarcarTodas.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				desmarcarTodas();
			}
		});
		btnDescarcarTodas.setBounds(181, 445, 146, 23);
		btnDescarcarTodas.setFocusable(false);
		contentPanel.add(btnDescarcarTodas);
		
		
		JLabel lblSeleccioneFallas = new JLabel(item.toString() );
		lblSeleccioneFallas.setFont(new Font("Tahoma", Font.PLAIN, 20));
		lblSeleccioneFallas.setHorizontalAlignment(SwingConstants.LEFT);
		lblSeleccioneFallas.setBounds(10, 21, 640, 27);
		contentPanel.add(lblSeleccioneFallas);
		
		list.addMouseListener(new MouseAdapter() {
		 public void mouseClicked(MouseEvent e) {
		   int index = list.locationToIndex(e.getPoint());
		   CheckableItem item = (CheckableItem) list.getModel()
		       .getElementAt(index);
		   item.setSelected(!item.isSelected());
		   Rectangle rect = list.getCellBounds(index, index);
		   list.repaint(rect);
		 }
		});
		//getContentPane().add(scrollPane, BorderLayout.CENTER);
		
		setModal(true);
		
		setVisible(true);
		
		keyAdapter = new KeyAdapter()
		{
		  public void keyPressed(KeyEvent e)
		  {
			  if(e.getKeyCode() == KeyEvent.VK_ENTER){
				   
				   //if(table.getSelectedRow() == table.getRowCount()-1){
				    	
				    	btnAceptar.doClick();
				    //}
				    //btnAceptar.requestFocus();
				   
			   }
			   
			   
			   
			   
			   if(e.getKeyCode() == KeyEvent.VK_SPACE){
					
				   btnMarcarTodas.doClick();
			   }
		  }
		}; 
		
		//scrollPane.addKeyListener(keyAdapter);
		contentPanel.getRootPane().setDefaultButton(btnAceptar);
		
	}

	private CheckableItem[] createLista(List strs) {
	    int n = strs.countItems();
	    CheckableItem[] items = new CheckableItem[n];
	    for (int i = 0; i < n; i++) 
	      items[i] = new CheckableItem(strs.getItem(i).toString());
	    
	    return items;
	  } 
	
	private boolean imprimirTodos() {
		boolean marco = false;
		bloque.atributo[indexItem].setEstado(true);
		
		ListModel model = list.getModel();
		int n = model.getSize();
		for (int i = 0; i < n; i++) {
			CheckableItem item = (CheckableItem) model.getElementAt(i);
		    
		     if (item.isSelected()) 
		     {
		    	 bloque.setEstado(false);
		    	 
		    	 if(!item.toString().equalsIgnoreCase("Otros")){
		    		 bloque.atributo[indexItem].addFalla(bloque.fallas[i].getId(),bloque.fallas[i].getFalla());
		    		 System.out.println(bloque.fallas[i].getFalla() + "  " + bloque.fallas[i].getId());
		    		
		    		 bloque.atributo[indexItem].setEstado(false);
		    		 System.out.println("Estado del bloque: "+ bloque.atributo[indexItem].getEstado());
		    	 }
		    	 else
		    	 {
		    		 bloque.atributo[indexItem].setEstado(false);
		    		 JPanel myPanel = new JPanel();
					 JLabel label1 = new JLabel("<html><h1>Ingrese la Falla</h1></html>");
					
					 final JTextField falla = new JTextField(20);
					 falla.setFont(new Font("Tahoma", Font.PLAIN, 20));
					
					 myPanel.add(label1);
					 myPanel.add(falla);
					// falla.requestFocus();
					
					// System.out.println("ASD: "+ bloque.atributo[indexItem].getEstado());
					/* falla.addKeyListener(new KeyAdapter() {
						 public void keyTyped(KeyEvent e) {
							 char caracter = e.getKeyChar();
							 if((((caracter < '0') ||  (caracter > '9')) && (caracter != KeyEvent.VK_BACK_SPACE))) {
								 e.consume();
							 }
						 }
					 });*/
						
					
					 falla.setText(falla.getText().replaceAll("\\s", ""));
					 while(falla.getText().equalsIgnoreCase("")){
						 JOptionPane.showMessageDialog(null, myPanel);
						 falla.setText(falla.getText().replaceAll("\\s", ""));
					 }
					 
					 //System.out.println("a poner: "+ falla.getText());           
                     bloque.atributo[indexItem].setFallaExtra(falla.getText());
                     //System.out.println("leo: "+ bloque.atributo[indexItem].getFallaExtra());  
		    		 
		       	 }
		    	 marco = true;
		    	 //bloque.atributo[indexItem].setEstado(false);
		     }
		     
		     
		     
		     
		   }
		   return marco;
	}
	
	private void marcarTodas() {
		ListModel model = list.getModel();
		   int n = model.getSize();
		   for (int i = 0; i < n; i++) {
			   CheckableItem item = (CheckableItem) model.getElementAt(i);
			   item.setSelected(true);
			   Rectangle rect = list.getCellBounds(i, i);
			   list.repaint(i);
		   }
	}
	
	private void desmarcarTodas() {
		ListModel model = list.getModel();
		   int n = model.getSize();
		   for (int i = 0; i < n; i++) {
			   CheckableItem item = (CheckableItem) model.getElementAt(i);
			   item.setSelected(false);
			   Rectangle rect = list.getCellBounds(i, i);
			   list.repaint(i);
		   }
	}
	
	
}